/*
 * Part of the ACID Project
 * Developed in 2011 by Morgan Taschuk
 */
package acid.spring.jdbc.repositories;

import acid.spring.db.Organism;
import acid.spring.jdbc.repositories.OrganismRepository;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import org.springframework.util.Assert;

/**
 *
 * @author morgan
 */
@Repository
public class JdbcOrganismRepository implements OrganismRepository, InitializingBean
{

    @Value("${jdbc.sql.organisms.listAll}")
    private String listAllOrganismsQuery;
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public void afterPropertiesSet() throws Exception
    {
        Assert.notNull(this.jdbcTemplate, "the jdbcTemplate can't be null!");
        Assert.notNull(this.listAllOrganismsQuery, "the listAllOrganismsQuery can't be null");
    }
    private RowMapper<Organism> organismRowMapper = new RowMapper<Organism>()
    {

        @Override
        public Organism mapRow(ResultSet resultSet, int i) throws SQLException
        {
            int id = resultSet.getInt("organism_id");
            String latinName = resultSet.getString("latin_name");
            String commonName = resultSet.getString("common_name");
            return new Organism(id, latinName, commonName);
        }
    };

    @Override
    public List<Organism> listAllOrganisms()
    {
        return jdbcTemplate.query(listAllOrganismsQuery, organismRowMapper);
    }
}
